// pages/user/login.js
const Controllers = require('../controllers/Controller.js').controller;
const request = require('../../utils/kzj.request.js');
const utils = require('../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      phone: '',
      code: ''
    },
    codeBtnText: '获取验证码',
    codeDisabled: true,
    subDisabled: true,
    isAgree: false,
    messageDialog: false,
    services: [
      {
        icon: '../../assets/images/login/signin_icon_01@2x.png',
        text: '在线客服',
        type: 'onLine'
      },
      {
        icon: '../../assets/images/login/signin_icon_02@2x.png',
        text: '客服热线',
        type: 'phone'
      },
      {
        icon: '../../assets/images/login/signin_icon_03@2x.png',
        text: '留言',
        type: 'message'
      }
    ],
    messageData: {
      contact: '',
      content: ''
    }
  },
  login() {
    var that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: request.url + '/api/account/agentAppletGetOpenId',
          data: { code: res.code },
          success(result) {
            console.log('appletLogin--result==', result);
            if(result.data.sessionKey){
              app.globalData.sessionKey=result.data.sessionKey
            }
            if(result.data.sessionId){
              wx.setStorageSync('token', result.data.sessionId)
            }
            app.globalData.openId=result.data.openId
            if (app.tokenReadyCallback) {
              app.tokenReadyCallback(result);
            }
          }
        })
      }
    });
  },
  getMessage(e) {
    var that = this;
    var name = e.target.dataset.name;
    var value = e.detail.value;
    var messageData = that.data.messageData;
    if (name === 'contact') {
      if (value.length === 11) {
        if (!utils.checkPhone(value)) {
          wx.showToast({
            title: '手机号码格式不正确',
            icon: 'none'
          });
          return;
        } else {
          messageData[name] = value;
          that.setData({
            messageData,
          });
        }
      }
      return;
    }
    messageData[name] = value;
    that.setData({
      messageData
    })
    console.log('that.data.messageData==', that.data.messageData);
  },
  onCancel(e) {
    var that = this;
    that.setData({
      messageData: {},
      messageDialog: false
    })
  },
  // 留言
  subMessage(e) {
    var that = this;
    var messageData = that.data.messageData;
    if (!messageData.contact || !messageData.content) {
      wx.showToast({
        title: '请填写正确的手机号码 和 内容',
        icon: 'none'
      });
      return;
    }
    Controllers.leaveMessage(messageData).then(res => {
      console.log('Controllers.leaveMessage--res==', res);
      const { code, data, desc } = res;
      wx.showToast({
        title: desc,
        icon: code === 1 ? 'success' : 'none'
      });
      that.setData({
        messageData: {},
        messageDialog: false
      });
    }).catch(err => {
      console.log('leaveMessage--catch--err==', err);
      wx.hideLoading()
      wx.showToast({
        title: err,
        icon: 'none'
      })
    })
  },
  showService(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    if (type === 'phone') {
      if (!that.data.configurePage || !that.data.configurePage.value) {
        wx.showToast({
          title: '抱歉，暂未获取客服热线',
          icon: 'none'
        })
        return;
      }
      wx.showModal({
        content: `客户电话：${that.data.configurePage.value}`,
        confirmText: '拨打',
        success(res) {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: that.data.configurePage.value
            })
          }
        }
      })
    } else if (type === 'message') {
      that.setData({
        messageDialog: true
      })
    }
  },
  // 登录;
  bindgetuserinfoBtn(e) {
    var that = this;
    var showToast = false;
    var title = '';
    if (!that.data.formData.phone) {
      showToast = true;
      title = '请输入验证码'
    } else if (!that.data.formData.code) {
      showToast = true;
      title = '请输入验证码'
    } else if (!that.data.isAgree) {
      showToast = true;
      title = '请同意协议';
    }
    console.log('bindgetuserinfoBtn--e==', e);
    if (showToast) {
      wx.showToast({
        title,
        icon: 'none'
      });
      return;
    }
    var params = {
      mobile: that.data.formData.phone,
      code: that.data.formData.code,
      openId: app.globalData.openId
    }
    wx.showLoading();
    Controllers.login(params).then(res => {
      console.log('Controllers.login--res==', res);
      const { code, data, desc } = res;
      wx.showToast({
        title: desc,
        icon: code === 1 ? 'success' : 'none'
      });
      if (code === 1) {
        // if (data && data.type === 4) {
        //   app.globalData.tabPage[1] = '/pages/Census/staff-index'
        // } else {
        //   app.globalData.tabPage[1] = '/pages/Census/index'
        // }
        wx.setStorageSync('tabPage', app.globalData.tabPage);
        wx.setStorageSync('token', data.sessionId);
        wx.setStorageSync('agentLogin', data);
        app.globalData.agentLogin = data;
        setTimeout(() => {
          wx.hideLoading();
          // app.openPage({url: app.globalData.tabPage[0], type: 'reLaunch'});
          app.openPage({url: '/pages/Census/selectIdentity/selectIdentity', type: 'reLaunch'});
        });
      }
    })
  },
  configurePage(no) {
    var that = this;
    console.log('configurePage--no==', no);
    Controllers.configurePage({no}).then(res => {
      console.log('configurePage--res==', res);
      const { code, data, desc } = res;
      that.setData({
        configurePage: data
      })
    }).catch(err => {
      console.log('configurePage--err==', err);
    })
  },
  changeAgree() {
    var that = this;
    if (that.data.formData.phone && that.data.formData.code && !that.data.isAgree) {
      that.data.subDisabled = false;
    } else {
      that.data.subDisabled = true;
    }
    that.setData({
      isAgree: !that.data.isAgree,
      subDisabled: that.data.subDisabled
    });
  },
  getInput(e) {
    var that = this;
    var name = e.target.dataset.name;
    var value = e.detail.value;
    var formData = that.data.formData;
    if (name === 'phone') {
      if (value.length === 11) {
        if (!utils.checkPhone(value)) {
          wx.showToast({
            title: '手机号码格式不正确',
            icon: 'none'
          });
          that.setData({
            codeDisabled: true
          })
          return;
        } else {
          formData[name] = value;
          var codeDisabled = true;
          if (!that.data.codeInterva) {
            codeDisabled = false;
          }
          that.setData({
            codeDisabled: codeDisabled,
            formData,
          });
        }
      } else {
        that.setData({
          codeDisabled: true
        });
      }
      return;
    }
    formData[name] = value;
    if (formData.phone && formData.code && that.data.isAgree) {
      that.data.subDisabled = false;
    } else {
      that.data.subDisabled = true;
    }
    that.setData({
      formData,
      subDisabled: that.data.subDisabled
    })
    console.log('that.data.formData==', that.data.formData);
  },
  getCode(e) {
    var that = this;
    var codeDisabled = that.data.codeDisabled;
    if (codeDisabled) {
      console.log('codeDisabled---return');
      return;
    }

    var params={
      mobile: that.data.formData.phone,
      type: 'Login',
      sendType: 3
    }
    // if (that.data.isLoading) {
    //   console.log('that.data.isLoading---return');
      
    //   return;
    // }
    that.data.isLoading = true;
    wx.showLoading();

    Controllers.getCode(params).then(res=>{
      console.log('getCode--res==', res);
      const { code, data, desc } = res;
      wx.hideLoading()
      wx.showToast({
        title: desc,
        icon: code === 1 ? 'success' : 'none'
      });
      if (code === 1) {
        var codeIntervalNumber = 60;
        var codeBtnText = '';
        that.setData({
          codeInterva:setInterval(() => {
            if (codeIntervalNumber > 1) {
              codeDisabled = true;
              codeIntervalNumber -= 1;
              codeBtnText = `${codeIntervalNumber}s`;
            } else {
              codeDisabled = false;
              codeBtnText = '获取验证码';
              clearInterval(that.data.codeInterva);
              that.setData({
                codeInterva:''
              })
            }
            that.setData({
              codeDisabled,
              codeBtnText
            })
          }, 1000)
        })

        // that.codeInterva = setInterval(() => {
        //   if (codeIntervalNumber > 1) {
        //     codeDisabled = true;
        //     codeIntervalNumber -= 1;
        //     codeBtnText = `${codeIntervalNumber}s`;
        //   } else {
        //     codeDisabled = false;
        //     codeBtnText = '获取验证码';
        //     clearInterval(that.codeInterva);
        //   }
        //   that.setData({
        //     codeDisabled,
        //     codeBtnText
        //   })
        // }, 1000);
      } else {
        console.log('that.data.isLoading--false');
        that.data.isLoading = false;
      }
    }).catch(res => {
      console.log('catch--res==', res);
      that.data.isLoading = false;
    })
  },
  openPage(e) {
    var url = e.currentTarget.dataset.url;
    if (url) {
      app.openPage({ url });
    } else {
      wx.showToast({
        title: '未获取页面路径',
        icon: 'none'
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    console.log('Login--app.globalData.openId==', app.globalData.openId)
    if (!app.globalData.openId) {
      that.login();
    }
    that.configurePage(2);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    if (that.codeInterva) {
      clearInterval(that.codeInterva);
    }
    that.setData({
      codeBtnText: '获取验证码',
      codeDisabled: true,
      subDisabled: true,
      isAgree: false,
      messageDialog: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})